Ext.define('AmpleHarvest.objects.Statistics.view.UserByOrg',
		{
			extend			: 'AmpleHarvest.objects.Statistics.absPanel',
			uses			:
			[
				'AmpleHarvest.DATA.Store.statistics.cUserByOrgTopOrgs'
			],
			requires						:
			[
//			 	"Ext.chart.*",
				"AmpleHarvest.objects.Statistics.LineFilter"
			],
			title			: 'Users By Organization (Top 5 Orgs)',
			
			layout			:
			{
				type	: 'vbox',
				align	: 'stretch'
			},
			html			: '<p></p>',

			loadChart		: function(target, series){
				target.m_obj_Chart = Ext.create('AmpleHarvest.objects.chart.cExportable',
							{
								animate	: true,
								title	: "Top Users By Organization",
								store	: target.getStore(),
								theme	: 'Base:gradients',
								flex			: 1,
								legend	:
								{
									position	: 'right'
								},
								
								axes	:
								[
										{
											type			: 'Numeric',
											position		: 'left',
											decimals		:	1,
											fields			:
											[
												'value'
											],
											/*label			:
											{
												renderer	: Ext.util.Format.numberRenderer('0,0')
											},*/
											title			: 'Users',
											grid			: true,
											minimum			: 0,
											minorTickSteps	: 0
											
										},
										{
											type		: 'Category',
											position	: 'bottom',
											fields		:
											[
												'date'
											],
											dateFormat: 'm-d-Y',
											label		:
											{
												//renderer	: Ext.util.Format.dateRenderer('m-d-Y'),
												rotate		:
												{
													degrees	: 315
												}
											},
											title		: 'Date',
											setLabels: function() {
										        var store = this.chart.store,
										            fields = this.fields,
										            ln = fields.length,
										            i;
										
										        this.labels = [];
										        var uniqueFields = {};
												
												
										        store.each(function(record) {
										            for (i = 0; i < ln; i++) {
										            	var field_value = record.get(fields[i]);
										            	if(!uniqueFields[field_value]){
											            	uniqueFields[field_value] =true;
											                this.labels.push(field_value);
											               // console.log('field_value: ' + field_value);
										                }
										            }
										        }, this);
										        return this.labels.length;
										    },
										
										    
										    applyData: function() {
										        this.callParent();
										        var count = this.setLabels();
										        return {
										            from: 0,
										            to: count,
										            power: 1,
										            step: 1,
										            steps: count - 1
										        };
										    }
										}
								],
								series	: series
								
							}
					);
					
					target.add( target.m_obj_Chart);
					target.setLoading(false);
					//target.add(target.m_obj_Chart);
					
					
			},
			
			
			buildSeries		: function(records){
		
			
				var orgs = {};
				//records = records.data.items;
				
				for(var i = 0; i < records.length; i++){
				    var org = records[i].raw.org;
				    orgs[org]=records[i].raw.org_label;
				}
				
				var series = [];
				
				for (var org in orgs){
					var label = orgs[org];
					series.push({
										type			: 'linefilter',
										xField			: 'date',
										yField			: 'value',
										axis			: 'left',
										title			: label,
										org				: org,
										showInLegend	: true,
										tips			:
										{
											trackMouse	: true,
											//width		: 200,
											//height		: 40,
											tpl			: new Ext.XTemplate("<div class='org-user-count-tooltip'>" +
																"<span class='user-count-label'>{date} </span></br>" +
																"<span class='user-count-label'>{value}</span>" +
																" <span class='user-count-label'>{org}</span> users</br>" +
															"</div>"),
											renderer	: function(
													obj_StoreItem, obj_Item)
											{
												// calculate and display
												// percentage on hover
												var item = obj_StoreItem.data;
												this.data = item;
												var el = this.getEl();
												if(el){
													this.tpl.overwrite(el, item);
												}
											}
										},
										highlight		:
										{
											segment	:
											{
												margin	: 20
											}
										}
							
									});
				}
				
				return series;
				
				},
				
			
			initComponent	: function()
			{
			
			var obj_This = this;
			
			var data_store = Ext
								.create('AmpleHarvest.DATA.Store.statistics.cUserByOrgTopOrgs',								
								{
									listeners: {
										load:  function(store,records, success) {										       
										         //console.log("General store load complete: " + records.length);
										        if(!obj_This.m_obj_Chart){											        
										        	var series = obj_This.buildSeries(records);
										        	obj_This.loadChart(obj_This, series);
										        }else{
										        	obj_This.remove(obj_This.m_obj_Chart);
										        	var series = obj_This.buildSeries(records);
										        	obj_This.loadChart(obj_This, series);
										        	obj_This.doLayout();
										        }
										    }
								    }
								});
			
						
				this
						.setStore(data_store);
			
			var past_days = Ext.create('Ext.data.Store', {
			    fields: ['name', 'value'],
			    data : [
			        {"name":"1", "value":"1 month"},
			        {"name":"2", "value":"2 months"},
			        {"name":"6", "value":"6 months"},
			        {"name":"12", "value":"1 year"}
			    ]
			});
			var obj_CurDate = new Date();
					this.m_obj_DateSelect = Ext.create('Ext.container.AbstractContainer',
				{
					layout			:
					{
						type			: 'hbox',
						defaultMargins	:
						{
							top		: 5,
							right	: 25,
							bottom	: 0,
							left	: 10
						}
					},

					m_obj_EndDate	: Ext.Date
							.add(obj_CurDate, Ext.Date.DAY, 1),
					m_obj_StartDate	: Ext.Date.add(obj_CurDate, Ext.Date.MONTH,
							-1
					),
					frame			: true,
					items			:
					[
							
							{
								xtype		: 'datefield',
								itemId 		: 'user-org-start-date',
								fieldLabel	: "Start Date",
								flex		: 1,
								labelWidth	: 75,
								enableKeyEvents: true,
								value		: Ext.Date.add(obj_CurDate,
										Ext.Date.MONTH, -1
								),
								listeners	:
								{
									'keyup'	:
									{
										fn		: function( field,  e,  eOpts)
										{
											//if the user hits the enter key
											//then act as if the update button was 
											//triggered
											if(e.keyCode == 13){
												var update = this.ownerCt.getComponent('user-org-update');
												update.fireEvent('click', update);
											}
											
										},
										scope	: this.ownerCt
									},
									scope		: this.ownerCt
								}
							},
							{
								xtype		: 'datefield',
								fieldLabel	: "End Date",
								itemId		: 'user-org-end-date',
								flex		: 1,
								labelWidth	: 75,
								enableKeyEvents: true,
								value		: Ext.Date.add(obj_CurDate,
										Ext.Date.DAY, 1
								),
								listeners	:
								{
									'keyup'	:
									{
										fn		: function( field,  e,  eOpts)
										{
											//if the user hits the enter key
											//then act as if the update button was 
											//triggered
											if(e.keyCode == 13){
												var update = this.ownerCt.getComponent('user-org-update');
												update.fireEvent('click', update);
											}
											
										},
										scope	: this.ownerCt
									},
									scope		: this.ownerCt
								}
							},
							{
								xtype	: "button",
								text	: "update",
								itemId  : 'user-org-update',
								listeners	:
								{
									'click'	:
									{
										fn		: function() {
											var owner = this.ownerCt;
											var start_date = owner.getComponent('user-org-start-date').rawValue;
											var end_date = owner.getComponent('user-org-end-date').rawValue;
											if(start_date && end_date){
												start_date = start_date.replace('/\//g','-');
												end_date = end_date.replace('/\//g','-');
											}
											
										       var store = obj_This.getStore();
														store.clearFilter();
														store.filter("start_date",start_date);
														store.filter("end_date",end_date);
														store.load({
														    scope   : this,
														    callback: function(records, operation, success) {
														    	//it seems that there needs to be some kind of a nudge
														    	//to let the chart know that something has been updated
														       obj_This.getStore().clearFilter();
														    }
														    });
										    },
										scope	: this.ownerCt
									},
									scope		: this.ownerCt
								}
							}
					]
				});

				
				
				
				
				
				//make a set of all the org names
				
      				this.callParent();
					this.getStore().on("beforeload", this.showMask, this);
					this.getStore().on("load", this.hideMask, this);
	
					this.on("render", this.updateData, this);
					
					this.add(this.m_obj_DateSelect);
					this.on("beforeload", this.showMask, this);
				
			}
		}
);